import { routeListMap } from '@/router'
import router from '@/router'

/**
 * 默认进入main页面的url 取值为第一个菜单的url
 */
export let defaultUrl: Record<string, any> = {}
/**
 * 根据菜单动态注册路由
 * @param userMenus 从接口获取的用户菜单
 */
export const mapMenusToRoutes = (userMenus: any[]) => {
  for (const menu of userMenus) {
    for (const subMenu of menu.children) {
      const route = routeListMap.find((item) => item.path === subMenu.url)
      if (route) {
        router.addRoute('main', route)
        if (!defaultUrl) {
          defaultUrl = subMenu
        }
      }
    }
  }
}

/**
 * 根据当前url路径找出对应的菜单
 * @param path 路由路径
 * @param userMenus 权限菜单
 */

export const findMenuByPath = (path: string, userMenus: any[]) => {
  for (const menu of userMenus) {
    for (const subMenu of menu.children) {
      if (subMenu.url === path) {
        return subMenu
      }
    }
  }
}

/**
 * 根据当前路径获取面包屑路径层级
 * @param path 路由路径
 * @param userMenus 用户权限菜单
 */
export const getCrumbsByPath = (path: string, userMenus: any[]) => {
  const crumbs: any[] = []
  for (const menu of userMenus) {
    for (const subMenu of menu.children) {
      if (subMenu.url === path) {
        crumbs.push({ name: menu.name, path: '' })
        crumbs.push({ name: subMenu.name, path: subMenu.url })
        return crumbs
      }
    }
  }
}
